<!--
 * @Author: liyin 2179253556@qq.com
 * @Date: 2023-12-18 15:55:20
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-10-16 09:10:53
 * @FilePath: MouthSecondBar.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <!-- 折线图和柱状图组合 -->
    <div class="MouthSecondBar">
        <div class="searchBox">
            <div class="leftFlex">
                <div class="lineBox" v-if="selectType != 4"><span></span>通话分钟均值</div>
            </div>
            <div class="rtFlex">
                <span>学校</span>
                <el-select size="small" v-model="personQuery.school" @change="Search" clearable filterable
                    style="width:210px" placeholder="请选择学校">
                    <el-option v-for="item in schoolList" :key="item.school" :label="item.school_name"
                        :value="item.school">
                    </el-option>
                </el-select>
                <span>日期</span>
                <el-date-picker size="small" style="width:210px" v-model="personQuery.datevalue" @change="changeDate"
                    :clearable="false" value-format="yyyy-MM-dd" type="date" placeholder="请选择日期"
                    :picker-options="pickerOptions">
                </el-date-picker>
            </div>
        </div>
        <div class="searchBox searchBox2">
            <div class="leftFlex">
                <div v-if="selectType != 4">通话分钟总数：<span>{{ secondsTotal.toFixed(2) }}分钟</span></div>
                <div v-if="selectType != 4">通话分钟均值：<span>{{ averageSeconds }}分钟</span></div>
                <div>通话总次数：{{ Math.ceil(countTotal) }}次</div>
                <div>通话次数均值：{{ Math.ceil(averageCount) }}次</div>
            </div>
            <div class="rtFlex">
                数据统计说明
                <el-tooltip class="item" effect="dark" content="Top Left 提示文字" placement="left">
                    <div slot="content">
                        <p> 说明：</p>
                        <p> 1、如果没有选学校,通话分钟数和通话次数统计的是所有学校的数据总和</p>
                        <p> 2、如果日期为空，统计当前日期近30天的数据</p>
                        <p> 3、如果选择了日期,统计选中日期近30天的数据</p>
                    </div>
                    <img :src="require('../assets/img/icon_tips.png')" />
                </el-tooltip>
            </div>
        </div>
        <div id="chart"></div>
    </div>
</template>
<script>
export default {
    name: 'MouthSecondBar',
    props: {
        MouthSecondDialog: {
            type: Boolean,
            default: false
        },
        schoolList: {
            type: Array,
            default: []
        },
        selectType: {
            type: Number,
            default: 0
        },
        datevalue: {
            type: String,
            default: ''
        },
    },
    data() {
        return {
            personQuery: {
                school: '',
                datevalue: ''
            },
            averageCount: 0,
            countTotal: 0,
            averageSeconds: 0,
            secondsTotal: 0,
            myChart: null,
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                }
            },
        }
    },
    watch: {
        MouthSecondDialog: {
            handler(newVal) {
                if (this.MouthSecondDialog) {
                    if (this.datevalue) {
                        this.personQuery.datevalue = this.datevalue
                    }
                    this.getInfo()
                }
            },
            deep: true,
            immediate: true
        },
    },
    mounted() {
        // this.getInfo()
        window.addEventListener('resize', () => {
            setTimeout(async () => {
                await this.myChart.resize()
            }, 100)
        })
    },
    methods: {
        Search() {
            this.getInfo()
        },
        // 切换时间的时候
        async changeDate() {
            this.getInfo()
        },
        // 求数据的平均值
        average(arr) {
            const sum = arr.reduce((a, b) => Number(a) + Number(b), 0);
            const avg = sum / arr.length;
            return avg.toFixed(2); // 保留两位小数
        },
        // 获取数据
        async getInfo() {
            const params = {
                school: this.personQuery.school,
                theDay: this.personQuery.datevalue,
                days: 30,
            }
            const { data: res } = await this.$http.get('/TalkScreen/Api/HlPhone/schoolCallDays', {
                params: params
            })
            await this.getChart(res.data)
        },
        total(data) {
            return data.reduce((sum, num) => Number(sum) + Number(num), 0);
        },
        total2(data) {
            return data.reduce((sum, num) => Number(sum) + Number(num), 0);
        },
        getChart(array) {
            let that = this
            that.myChart = that.$echarts.init(document.getElementById('chart'))
            var dataOne = [] // 通话次数
            var dataTwo = [] // 通话时长
            var typeList = [] // 横坐标展示的日期
            array.forEach((item, index) => {
                if (Number(this.selectType) === 1) {
                    dataOne.push(Number(item.callCount))
                    dataTwo.push(Number(item.callSecond) !== 0 ? (Number(item.callSecond) / 60).toFixed(2) : 0)
                } else if (Number(this.selectType) === 2) {
                    dataOne.push(Number(item.successCount))
                    dataTwo.push(Number(item.normalCallSecond) !== 0 ? (Number(item.normalCallSecond) / 60).toFixed(2) : 0)
                } else if (Number(this.selectType) === 3) {
                    dataOne.push(Number(item.shortSuccessCount))
                    dataTwo.push(Number(item.shortCallSecond) !== 0 ? (Number(item.shortCallSecond) / 60).toFixed(2) : 0)
                } else {
                    dataOne.push(Number(item.failCount))
                    dataTwo.push(0)
                }
                typeList.push(item.callDay.slice(5))
            })
            this.countTotal = this.total(dataOne)
            this.secondsTotal = this.total2(dataTwo)
            let arrList = [...dataOne, ...dataTwo]
            that.averageCount = that.average(dataOne)
            that.averageSeconds = that.average(dataTwo)
            // 获取坐标轴刻度最大值
            let maxVal = Number(Math.max(...arrList)) + 10;
            // 获取坐标轴刻度最小值
            let minVal = Number(Math.min(...arrList)) + 10;
            // 计算坐标轴分割间隔
            let interval = Math.floor((maxVal - minVal) / 5);
            let color = ['#25C5B4', '#5B8FF9']
            var option = {
                color: color,
                title: {
                    // text: `单位/${Number(that.activeName) === 1 ? '次' : '千次'}`,
                    top: that.$util.nowSizeWidth(55),
                    left: -5,
                    textStyle: {
                        color: '#FFFFFF',
                        fontSize: that.$util.nowSizeWidth(12),
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: "#fff",
                    extraCssText: "box-shadow: 0px 9px 28px 1px rgba(0,0,0,0.05);",
                    formatter: function (params) {
                        return (
                            `<span style='font-size: 12px;
                                font-family: Source Han Sans CN, Source Han Sans CN;
                                font-weight: bold;
                                color: #0A1F48;width:100%;text-align: center;margin-bottom:4px;display:inline-block;text-align: left;'>${params[0].axisValue}通话统计</span>` +
                            `<br>` +
                            params
                                .map((item, index) => {
                                    let str = `<span style="display:inline-block;vertical-align: middle;width:8px;height:8px;margin: 0 5px 0 0px;background-color:${color[index]};"></span>`
                                    let seriesNameStr = `<span style="display:inline-block;font-size:12px;vertical-align: middle;">${item.seriesName}</span>`
                                    let value = item.value
                                    let valueStr = `<span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;">${value} ${params[index].seriesName == '通话次数' ? '次' : '分钟'}</span>`
                                    return `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
									<span>${str}${seriesNameStr}</span>
									<span>${valueStr}</span>
								</span>`
                                })
                                .join(``)
                        )
                    },
                },
                grid: {
                    left: 0,
                    right: 0,
                    bottom: 0,
                    top: that.$util.nowSizeWidth(120),
                    containLabel: true
                },
                legend: {
                    orient: 'horizontal',
                    icon: 'rect',
                    top: that.$util.nowSizeWidth(22),
                    left: 0,
                    itemWidth: 12,
                    itemHeight: 12,
                    textStyle: {
                        color: '#fff',
                        fontSize: that.$util.nowSizeWidth(14),
                        rich: {
                            a: {
                                verticalAlign: 'middle',
                            },
                        },
                        padding: [2, 10, 0, 10],
                    },
                    itemGap: 30,//间距
                    data: ['通话次数', '通话分钟']
                },
                xAxis: [
                    {
                        type: 'category',
                        axisLine: {
                            lineStyle: {
                                type: 'solid',
                                color: '#0D3B77',//左边线的颜色
                                width: '1'//坐标线的宽度
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#ffffff',//坐标值得具体的颜色
                            },
                            interval: 0
                        },
                        axisTick: false,
                        data: typeList
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        // min: minVal, // 坐标轴刻度最小值。
                        // max: maxVal, // 坐标轴刻度最大值。
                        // interval: interval, // 强制设置坐标轴分割间隔。
                        minInterval: 1,
                        scale: true,
                        axisLine: {
                            lineStyle: {
                                type: 'solid',
                                color: '#2E3950',//左边线的颜色
                                width: '1',//坐标线的宽度
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#e6e6e6',//坐标值得具体的颜色
                            }
                        },
                        axisTick: false,
                        splitLine: {  //坐标轴在grid区域中的分隔线（网格中的横线）
                            show: true,
                            lineStyle: {
                                color: ['#0D3B77'],
                                width: 1,
                                type: 'solid',
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: '通话次数',
                        type: 'bar',
                        activeName: that.activeName,
                        barGap: 0,
                        barWidth: '30%',
                        itemStyle: {
                            normal: {
                                color: '#27CEBA'
                            },
                        },
                        data: dataOne
                    },
                    {
                        name: '通话分钟',
                        type: 'bar',
                        activeName: that.activeName,
                        barGap: 0,
                        barWidth: '30%',
                        itemStyle: {
                            normal: {
                                color: '#5B8FF9'
                            },
                        },
                        data: that.selectType === 4 ? [] : dataTwo,
                        markLine: {
                            data: [
                                {
                                    name: '平均值',
                                    type: 'average',
                                    yAxis: that.average(dataTwo),
                                    lineStyle: {
                                        color: '#F6C748',    // 线条颜色
                                        width: 1,       // 线条宽度
                                        type: 'dashed',    // 线条类型，默认为实线，可选：'solid', 'dashed', 'dotted'
                                        opacity: that.selectType === 4 ? 0 : 1　　//线条透明度设置为0
                                    },

                                    label: {
                                        fontSize: 0,
                                        formatter: '平均值: ' + '{c}' + ' 单位' // 自定义标签格式
                                    }
                                }
                            ],

                        }
                    }
                ]
            }
            that.myChart.setOption(option, true)
        },
    }
}
</script>
<style lang="less" scoped>
.MouthSecondBar {
    width: 100%;
    height: 100%;
    background: #0A1F48;
    position: relative;
    padding: 0 20px;
    box-sizing: border-box;

    #chart {
        width: 100%;
        height: 100%;
    }

    .searchBox {
        width: calc(100% - 40px);
        top: 15px;
        padding-left: 220px;
        position: absolute;
        display: flex;
        align-items: center;
        justify-content: space-between;
        z-index: 9999;

        .leftFlex {
            font-size: 14px;

            .lineBox {
                font-size: 14px;

                span {
                    vertical-align: middle;
                    display: inline-block;
                    width: 18px;
                    height: 2px;
                    background: #F6C748;
                    margin-right: 10px;
                }
            }

            div {
                display: inline-block;
                padding: 0 15px;

                span {
                    color: #F6C748;
                }
            }
        }

        .rtFlex {
            font-size: 14px;
            color: #ACD3FC;

            span {
                display: inline-block;
                padding: 0 10px 0 30px;
            }
        }

    }

    .searchBox2 {
        top: 65px;
        left: 0px;
        padding-left: 10px;
        padding-right: 20px;
        width: 100%;
        box-sizing: border-box;

        .leftFlex {
            flex: 1;
            text-align: left;
        }

        .rtFlex {
            display: flex;
            align-content: center;
            text-align: right;

            img {
                display: inline-block;
                margin-left: 8px;
                width: 18px;
                height: 18px;
            }
        }
    }
}
</style>